package com.lottery.controller.pc28.lobbyController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lottery.dto.ResultDto;
import com.lottery.service.pc28.JedisClient;
import com.lottery.service.pc28.lobbyService.LotteryService;
import com.lottery.service.pc28.lobbyService.MyOrderService;
import com.lottery.service.pc28.lobbyService.WinningResultsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/homepage")
public class HomepageController {
	@Autowired
	private LotteryService lotteryService;

	@Autowired
	private JedisClient jedisClient;

	@Autowired
	private WinningResultsService winningResultsService;

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private MyOrderService myOrderService;

	// pc28中奖信息标志key
	@Value("${PC28FLG}")
	private String FLG;

	// Ssc中奖信息标志key
	@Value("${SSCFLG}")
	private String SSCFLG;

	// 当前开奖的期号
	@Value("${PC28EXPECT}")
	private String PC28EXPECT;
	@Value("${SSCEXPECT}")
	private String SSCEXPECT;

	/**
	 * 往期开奖记录
	 * 
	 * @param pageNow
	 *            当前页数
	 * 
	 * @param pageSize
	 *            每页记录条数
	 * 
	 * 
	 * @return
	 */
	@CrossOrigin
	@RequestMapping(value = "/public/past", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public String getNotice(HttpServletRequest request) {
		JSONObject jObject = new JSONObject();
		String body = "";
		try {
			body = readHttpBody(request);
			JSONObject obj = JSONObject.parseObject(body);

			logger.info("getNotice={}*******************", body);
			int pageNow = obj.getInteger("pageNow");
			int pageSize = obj.getInteger("pageSize");
			String expect = obj.getString("expect");
			// type待处理
			int lotteyType = obj.getInteger("lotteyType");
			logger.info("查询往期开奖记录的数据={}", "当前页数:" + pageNow + "  查询条数:" + pageSize + "  查询期号:" + expect);

			String selectLotteryList = lotteryService.selectLotteryList(pageNow, pageSize, expect, lotteyType);
			logger.info("往期开奖记录={}", selectLotteryList);
			return selectLotteryList;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("*****getNotice error******:", e);
			jObject.put("result", "1");
			jObject.put("msg", "失败!");
		}
		return jObject.toJSONString();
	}

	/**
	 * 查询中奖的结果,提示用户是否中奖
	 * 
	 * @param user_id
	 *            客户id
	 * 
	 * @return
	 */
	@CrossOrigin
	@RequestMapping(value = "/winningResults", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public String selectWinningResultsService(HttpServletRequest request) {
		logger.info(".....................进来了");
		String body = "";
		try {
			body = readHttpBody(request);
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("*****selectWinningResultsService error******:", e);
		}
		JSONObject obj = JSONObject.parseObject(body);
		// 实例化结果集
		ResultDto<Map<String, Object>> maxMap = new ResultDto<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		// 获取期号
		Integer lotteyType = obj.getInteger("lotteyType");
		String jsonToList = "";
		String expect = "";
		try {
			// 获取页面user_id
			String userId = String.valueOf(obj.getInteger("userId"));
			if (lotteyType == 2) {
				jsonToList = jedisClient.hget(FLG, userId);
				expect = jedisClient.get(PC28EXPECT);
			} else if (lotteyType == 1) {
				jsonToList = jedisClient.hget(SSCFLG, userId);
				expect = jedisClient.get(SSCEXPECT);
			}

			logger.info("get redis {}--{}", userId, jsonToList);
			// 反序列化
			// if (!StringUtils.isEmpty(jsonToList)) {
			// List<String> jsonlist = JsonUtils.jsonToList(jsonToList,
			// String.class);
			// map.put("jsonlist", jsonlist);
			// } else {
			// map.put("jsonlist", jsonToList);
			// }
			map.put("jsonlist", jsonToList);
			map.put("expect", expect);
			map.put("result", "0");
			map.put("msg", "成功");
			maxMap.setData(map);
			logger.info("查询用户中奖信息={}", "用户id:" + userId + "  中奖信息:" + maxMap);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("*****selectWinningResultsService error******:", e);
			map.put("result", "1");
			map.put("msg", "异常");
			maxMap.setData(map);
		}
		logger.info("查询用户中奖信息=*******************{}", JSON.toJSONString(maxMap, true));
		String json = JSON.toJSONString(maxMap, true);
		return json;

	}

	/**
	 * 开奖首页记录
	 * 
	 * @return
	 */
	@CrossOrigin
	@RequestMapping(value = "/public/showPage", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public String showPage(HttpServletRequest request) {
		String body = "";
		String showPage = "";
		try {
			body = readHttpBody(request);
			JSONObject obj = JSONObject.parseObject(body);
			logger.debug("************body****************{}", body);
			// type待处理
			Integer lotteyType = obj.getInteger("lotteyType");
			logger.debug("***********showPage lotteyType*****************{}", lotteyType);
			showPage = winningResultsService.showPage(lotteyType);
			logger.info("开奖首页记录={}", showPage);
			return showPage;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("showPage error", e);
		}
		return showPage;

	}

	/**
	 * 我的订单
	 */
	@CrossOrigin
	@RequestMapping(value = "/myOrder", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public String selectMyOrder(HttpServletRequest request) {
		JSONObject jObject = new JSONObject();
		String body = "";
		try {
			body = readHttpBody(request);
			JSONObject obj = JSONObject.parseObject(body);
			int userId = obj.getInteger("userId");
			int pageSize = obj.getInteger("pageSize");
			int pageNow = obj.getInteger("pageNow");
			/** 测试用例待修改 **/
			Integer lotteyType = 0;
			jObject.put("result", "0");
			jObject.put("msg", "成功");
			return myOrderService.selectMyOrderByUserId(userId, pageSize, pageNow, lotteyType);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("*****selectMyOrder error******:", e);
			jObject.put("result", "1");
			jObject.put("msg", "失败");
		}

		return jObject.toJSONString();
	}

	/**
	 * qiuqiudazhuozhanUse
	 * 订单详情表
	 * 
	 * @param request
	 * @return
	 */
	@CrossOrigin
	@RequestMapping(value = "/orderDetails", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public String orderDetails(HttpServletRequest request) {
		JSONObject jObject = new JSONObject();
		String body = "";
		try {
			body = readHttpBody(request);
			JSONObject obj = JSONObject.parseObject(body);
			int userId = obj.getInteger("userId");
			String expect = obj.getString("expect");
			int pageSize = obj.getInteger("pageSize");
			int pageNow = obj.getInteger("pageNow");
			jObject.put("result", "0");
			jObject.put("msg", "成功");
			return JSON.toJSONString(myOrderService.orderDetails(userId, expect, pageSize, pageNow), true);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("*****orderDetails error******:", e);
			jObject.put("result", "1");
			jObject.put("msg", "失败");
		}
		return jObject.toJSONString();
	}

	/**
	 * 获取广告图片
	 * 
	 * @return
	 */
	@CrossOrigin
	@RequestMapping(value = "/public/getadpicture", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public String getAdpicture(HttpServletRequest request) {
		JSONObject jObject = new JSONObject();
		String body = "";
		try {
			body = readHttpBody(request);
			JSONObject obj = JSONObject.parseObject(body);

			logger.info("getAdpicture={}*******************", body);
			String ret = lotteryService.getAdpicturer();
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("*****getAdpicture error******:", e);
			jObject.put("result", "1");
			jObject.put("msg", "失败!");
		}
		return jObject.toJSONString();
	}

	/**
	 * 获取赔率
	 * 
	 * @return
	 */
	@CrossOrigin
	@RequestMapping(value = "/public/getlotteryodds", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public String getlotteryOdds(HttpServletRequest request) {
		JSONObject jObject = new JSONObject();
		String body = "";
		try {
			body = readHttpBody(request);
			JSONObject obj = JSONObject.parseObject(body);

			logger.info("getlotteryodds={}*******************", body);
			String ret = lotteryService.getLotteryOdds();
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("*****getlotteryodds error******:", e);
			jObject.put("result", "1");
			jObject.put("msg", "失败!");
		}
		return jObject.toJSONString();
	}

	/**
	 * 解析json
	 * 
	 * @param request
	 * @return
	 * @throws IOException
	 */
	private String readHttpBody(HttpServletRequest request) throws IOException {

		// 读取input流
		/*
		 * BufferedReader br = new BufferedReader( new
		 * InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
		 * StringBuffer sb = new StringBuffer(""); String temp; while ((temp =
		 * br.readLine()) != null) { sb.append(temp); } br.close(); return
		 * sb.toString();
		 */

		String attribute = (String) request.getAttribute("json");
		return attribute;
	}

}
